﻿// Allows the component to show a context menu on a right click even
define([
'Xjs/core/util',
'Xjs/core/dom',
'Xjs/core/viewport',
'Xjs/app', // Ensure the creation of the global Xjs
'Xjs/ui/menu/Menu' // Include the menu,

],
function (util, dom, viewport) {
    'use strict';

    var type = 'contextMenuHolder', // Use the type registration to avoid recreating the type
    ContextMenuHolder = Xjs.getType(type);

    if (ContextMenuHolder) { // It has been already loaded
        return ContextMenuHolder;
    }

    // Renders the html from a component
    ContextMenuHolder = util.define({

        type: type, // Set the type

        initialize: function (conf) {

            conf = conf || {};

            if (conf.contextMenu) {
                this.enableContextMenu(conf.contextMenu);
            }
        },

        enableContextMenu: function (conf) {

            conf = conf || {};

            var me = this;
            me.contextMenu = Xjs.create('menu', conf, this);

            // Register the events
            me.addHandler('onRender', function () {

                var menu = me.contextMenu;

                me.on('contextmenu', function (evt) {

                    evt.preventDefault();
                    evt.stopPropagation();

                    if (me.tooltip) {
                        me.tooltip.setVisible(false);
                    }

                    var xOffset = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft),
                    yOffset = Math.max(document.documentElement.scrollTop, document.body.scrollTop);

                    menu.move(evt.clientX + xOffset, evt.clientY + yOffset);
                    viewport.adjust(menu.id); // Make sure it is completely visible inside the viewport
                    menu.setVisible(true);
                });

                me.on('click', function (evt) {
                    if (me.contextMenu.visible) {
                        me.contextMenu.setVisible(false);
                    }
                });
            });
        },

        // Context menu needs to be separated from its parent control to separate the event of the menu from its parent
        onBeforeAppend: function () {
            if (this.contextMenu) {
                this.contextMenu.appendTo(dom.getBody());
            }
        }
    });

    Xjs.registerType(ContextMenuHolder);

    return ContextMenuHolder;
});